<script setup>
import * as API from '@/api/deal/deal-product.js'
import {reqCascaderData} from '@/api/deal/deal-product.js'
import {ref, reactive, onMounted} from 'vue'
import {getLocalTime} from "@/utils/time.js";
import {ElMessage} from "element-plus";
import {reqNameList as reqProductTypeList} from "@/api/store/product.js";
// 用于表格
const pn = ref(1)
const ps = ref(10)
const total = ref(0)
const orderList = ref([])
const orderStatus = [
  {label:"交易中", value: 0, type: "danger"},
  {label:"交易完成", value: 1, type: "success"}
]
const orderType = [
  {label: "购买", value: 0},
  {label: '赠送', value: 1},
  {label: '空袋兑换', value: 2},
]

// 搜索框
const searchOptions = reactive({
  multistageOptions: {
    storeId: null,
    clerkId: null,
    customerId: null,
  },
  productId: null,
  timeRange: [null, null],
  dealStatus: null,
})


const handleTimeRangeChange = (value) => {
  if (!value) {
    searchOptions.timeRange = [null, null]; // 确保在清空时，数组也完全重置
  }
}

const clearTimeRange = () => {
  searchOptions.timeRange = [null, null]; // 在用户手动清空时重置
}

// 级联选择器 搜索 | 表单项
const optionTreeValue = ref([])
const optionsTree = ref([])
const productTypeList = ref([])
const optionTreeHandler = (value)=>{
  if (!value || value.length === 0) {
    // 当级联选择器清空时，将 multistageOptions 的所有属性清空
    searchOptions.multistageOptions.storeId = null;
    searchOptions.multistageOptions.clerkId = null;
    searchOptions.multistageOptions.customerId = null;
  } else {
    // 正常处理级联选择器的选中值
    searchOptions.multistageOptions.storeId = value[0] || null;
    searchOptions.multistageOptions.clerkId = value[1] || null;
    searchOptions.multistageOptions.customerId = value[2] || null;
  }
}

//用于表单
const dialogFormVisible = ref(false)
const orderParams = reactive({
  id: null,
  storeId: null,
  clerkId: null,
  customerId: null,
  productId: null,
  dealTime: null,
  type: null,
  totalNumber: null,
  totalPayment: null,
  notes: null,
})
const optionTreeValueForm = ref([])
const optionTreeFormHandler = (value)=>{
  if (!value || value.length === 0) {
    // 当级联选择器清空时，将 multistageOptions 的所有属性清空
    orderParams.storeId = null
    orderParams.clerkId = null
    orderParams.customerId = null
  } else {
    orderParams.storeId = value[0] || null
    orderParams.clerkId = value[1] || null
    orderParams.customerId = value[2] || null
  }
}


const getPage = async (pager = 1)=>{
  pn.value = pager
  const result = await API.reqPage(
      pn.value,
      ps.value,
      searchOptions.multistageOptions.storeId,
      searchOptions.multistageOptions.clerkId,
      searchOptions.multistageOptions.customerId,
      searchOptions.productId,
      searchOptions.timeRange[0],
      searchOptions.timeRange[1],
      searchOptions.dealStatus
  )
  if(result.code === "0"){
    total.value = result.data.total
    orderList.value = result.data.items
  } else {
    ElMessage({type:"error", message:"获取数据失败！"})
  }
}

// const reqExport = async ()=>{
//   API.reqExport().then(resp => {
//     if (resp != null) {
//       ElMessage({
//         message: '导出成功',
//         type: 'success',
//       })
//       const link = document.createElement('a')
//       link.href = URL.createObjectURL(resp)
//       link.download = 'data.xlsx'
//       link.click()
//       URL.revokeObjectURL(link.href)
//     }
//   })
// }

const addOrder = ()=>{
  dialogFormVisible.value = true
  Object.assign(orderParams,{
    id: null,
    storeId: null,
    clerkId: null,
    customerId: null,
    productId: null,
    dealTime: null,
    type: null,
    totalNumber: null,
    totalPayment: null,
    notes: null,
  })
  optionTreeValueForm.value = [null, null, null]
}

const updateOrder = (row)=>{
  dialogFormVisible.value = true
  Object.assign(orderParams,row)
  optionTreeValueForm.value = [
    orderParams.storeId,
    orderParams.clerkId,
    orderParams.customerId,
  ]
}

const deleteOrder = async (id)=>{
  const result = await API.reqDelete(id)
  if (result.code === '0') {
    ElMessage({ type: 'success', message: '删除成功' })
    await getPage(orderList.value.length > 1 ? pn.value : pn.value - 1);
  }
}

const cancel = ()=>{
  dialogFormVisible.value = false
}

const confirm = async ()=>{
  let result
  if(orderParams.id){
    result = await API.reqUpdate(orderParams)
  }else{
    result = await API.reqSave(orderParams)
  }
  if (result.code === '0') {
    ElMessage({ type: 'success', message: orderParams.id? '修改成功':'添加成功',})
    dialogFormVisible.value = false
    await getPage()
  } else {
    dialogFormVisible.value = false
    //提示消息
    ElMessage({ type: 'error', message: orderParams.id ? '修改失败':'添加失败' });
  }
}

const search = async ()=>{
  await getPage()
}

onMounted(()=>{
  //获取级联树
  reqCascaderData().then(resp => {
    optionsTree.value = resp.data.nameIdList
  })
  //获取商品类型列表
  reqProductTypeList().then(resp=>{
    productTypeList.value = resp.data.items
  })
  getPage()
})
</script>

<template>
  <!-- ----------------------------------- search ----------------------------------- -->
  <el-card>
    <el-scrollbar>
      <el-form class="search-card">
        <div class="search-input">
            <el-cascader
                placeholder="客户名"
                v-model="optionTreeValue"
                :options="optionsTree"
                @change="optionTreeHandler"
                expandTrigger="hover"
                :props="{ value: 'id', label: 'name', children: 'childrenList', checkStrictly: true, }"
                clearable
                filterable
            />
          <el-form-item>
            <el-select v-model="searchOptions.productId" clearable placeholder="货品名" style="width:180px">
              <el-option
                  v-for="item in productTypeList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="时间">
            <el-date-picker
                v-model="searchOptions.timeRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                value-format="YYYY-MM-DD"
                @change="handleTimeRangeChange"
                @clear="clearTimeRange"
            />
          </el-form-item>
          <el-form-item label="交易状态">
            <el-select v-model="searchOptions.dealStatus" clearable placeholder="交易状态" style="width:180px">
              <el-option
                  v-for="item in orderStatus"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
              />
            </el-select>
          </el-form-item>
        </div>
        <el-form-item>
          <el-button type="primary" size="default" @click="search" >搜索</el-button>
        </el-form-item>
      </el-form>
    </el-scrollbar>
  </el-card>
  <!-- ----------------------------------- search ----------------------------------- -->

  <!-- ----------------------------------- table ----------------------------------- -->
  <el-card>
    <el-button type="primary" size="default" @click="addOrder">添加</el-button>
    <!-- <el-button type="primary" size="default" @click="reqExport">导出</el-button> -->

    <el-table  style="margin: 10px 0;" border :data="orderList">
      <el-table-column label="#" align="center" type="index"></el-table-column>
      <el-table-column label="订单编号" align="center" prop="id" show-overflow-tooltip></el-table-column>
      <el-table-column label="分店名" align="center" prop="storeName" show-overflow-tooltip></el-table-column>
      <el-table-column label="店员名" align="center" prop="clerkName" show-overflow-tooltip></el-table-column>
      <el-table-column label="客户名" align="center" prop="customerName" show-overflow-tooltip></el-table-column>
      <el-table-column label="货品名" align="center" prop="productName" show-overflow-tooltip></el-table-column>
      <el-table-column label="交易时间" align="center" prop="dealTime" show-overflow-tooltip>
        <template #="{row}">
          <span>{{getLocalTime(row.dealTime, 1)}}</span>
        </template>
      </el-table-column>
      <el-table-column label="交易方式" align="center" prop="type" show-overflow-tooltip>
        <template #default="{row}">
          <span>{{orderType[row.type].label}}</span>
        </template>
      </el-table-column>
      <el-table-column label="已交易数量 / 总交易数量" align="center" show-overflow-tooltip>
        <template #default="{ row }">
          <span :style="{ color: row.currentNumber === row.totalNumber ? 'green' : 'red' }">
            {{ row.currentNumber }} / {{ row.totalNumber }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="已交易金额 / 总交易金额" align="center" show-overflow-tooltip>
        <template #default="{ row }">
          <span :style="{ color: row.currentPayment === row.totalPayment ? 'green' : 'red' }">
          {{ row.currentPayment }} / {{ row.totalPayment }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="交易状态" align="center" prop="dealStatus" width="95px" show-overflow-tooltip>
        <template #="{row}">
          <el-tag :type="orderStatus[row.dealStatus].type">{{orderStatus[row.dealStatus].label}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="notes" show-overflow-tooltip></el-table-column>
      <el-table-column label="创建/修改时间" align="center" prop="createTime" show-overflow-tooltip>
        <template #="{row}">
          <span>{{getLocalTime(row.createTime)}}</span>
          <br/>
          <span>{{getLocalTime(row.updateTime)}}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200px" align="center">
        <template #="{ row }">
          <el-row>
            <el-col :span="12">
              <el-button type="primary" size="small" icon="Edit" @click="updateOrder(row)">编辑</el-button>
            </el-col>
            <el-col :span="12">
              <el-popconfirm :title="`确定要删除?`" width="260px" @confirm="deleteOrder(row.id)">
                <template #reference>
                  <el-button type="primary" size="small" icon="Delete">删除</el-button>
                </template>
              </el-popconfirm>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
               <el-button type="info" size="small" icon="Edit">
                  <RouterLink :to="`/log/deal/product-number/?dealProductId=${row.id}`">数量管理</RouterLink>
               </el-button>
            </el-col>
            <el-col :span="12">
               <el-button type="warning" size="small" icon="Edit">
                  <RouterLink :to="`/log/deal/product-payment/?dealProductId=${row.id}`">货款管理</RouterLink>
               </el-button>
            </el-col>
          </el-row>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
        @size-change="getPage()"
        @current-change="getPage"
        v-model:current-page="pn"
        v-model:page-size="ps"
        :page-sizes="[10, 20, 50, 100]"
        :background="true"
        layout="prev, pager, next, jumper, ->, sizes, total"
        :total="total"
    />
  </el-card>
  <!-- ----------------------------------- table ----------------------------------- -->

  <!-- ----------------------------------- dialog ----------------------------------- -->
  <el-dialog
      v-model="dialogFormVisible"
      :title="orderParams.id? '修改订单' : '添加订单'"
  >
    <el-form style="width: 80%" :model="orderParams">
      <el-form-item label="客户名"  label-width="100px">
        <el-cascader
            placeholder="客户名"
            v-model="optionTreeValueForm"
            :options="optionsTree"
            @change="optionTreeFormHandler"
            expandTrigger="hover"
            :props="{ value: 'id', label: 'name', children: 'childrenList', }"
            clearable
            filterable
        />
      </el-form-item>
      <el-form-item label="货品名"  label-width="100px">
        <el-select v-model="orderParams.productId" clearable placeholder="货品名" style="width:200px">
          <el-option
              v-for="item in productTypeList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="交易时间" label-width="100px">
        <el-date-picker
            v-model="orderParams.dealTime"
            type="date"
            placeholder="交易时间"
        />
      </el-form-item>
      <el-form-item label="交易方式"  label-width="100px">
        <el-select v-model="orderParams.type" clearable placeholder="交易方式" style="width:200px">
          <el-option
              v-for="item in orderType"
              :key="item.value"
              :label="item.label"
              :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="总数量" label-width="100px">
        <el-input v-model="orderParams.totalNumber"></el-input>
      </el-form-item>
      <el-form-item label="总金额" label-width="100px">
        <el-input v-model="orderParams.totalPayment"></el-input>
      </el-form-item>
      <el-form-item label="备注" label-width="100px">
        <el-input v-model="orderParams.notes" type="textarea"></el-input>
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button type="primary" size="default" @click="cancel">取消</el-button>
      <el-button type="primary" size="default" @click="confirm">确定</el-button>
    </template>
  </el-dialog>
  <!-- ----------------------------------- dialog ----------------------------------- -->
</template>

<style scoped lang="css">
.search-card {
  display: flex;
  align-items: center;
  flex-direction: row;
  flex-wrap: wrap;
  margin-bottom: 1rem;
  padding: 1rem;
  background-color: #f9f9f9;
  border-radius: 8px;
}
.search-input {
  display: flex;
  align-items: center;
  flex: 1 0 auto;
  gap: 1rem;
}
.search-input > * {
  flex: 0 1 auto;
}
.el-form-item {
  margin-bottom: 0;
  display: flex;
  align-items: center;
}
.el-form-item label {
  width: 80px; /* Adjust this value as needed */
}
.el-card {
  margin-bottom: 1rem;
}
.el-table {
  margin: 1rem 0;
}
.el-dialog {
  width: 50%;
}
.el-dialog .el-form-item {
  margin-bottom: 1rem;
}
.el-dialog .el-form-item p {
  margin-bottom: 0.5rem;
}
.el-dialog .el-form-item label {
  width: 120px; /* Adjusted width for better alignment */
}
.el-dialog .el-form-item .el-input,
.el-dialog .el-form-item .el-select,
.el-dialog .el-form-item .el-date-picker {
  width: calc(100% - 130px); /* Adjusted width to fit the label */
}
</style>